import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { plainToInstance } from 'class-transformer';
import { Observable, map } from 'rxjs';

@Injectable()
export class SerializeInterceptor implements NestInterceptor {
  constructor(private dto: any) {}
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    // const req = context.switchToHttp().getRequest();
    // console.log('拦截器执行之前', req);
    return next.handle().pipe(
      map(data => {
        // console.log('拦截器执行之后', data);

        return plainToInstance(this.dto, data, {
          // 排除所有不设置Expose的属性
          excludeExtraneousValues: true,
        })
      })
    )
  }
}
